package com.superlc.ssm.modular.api.service.imp;

import com.superlc.ssm.modular.api.model.UserOnline;
import com.superlc.ssm.modular.api.service.SessionService;
import com.superlc.ssm.modular.sys.model.UserInfo;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author super
 */
@Service
public class SessionServiceImp implements SessionService {

    @Autowired
    private SessionDAO sessionDAO ;


    @Override
    public List<UserOnline> list() {
        List<UserOnline> userList = new ArrayList<>();
        Collection<Session>  sessions = sessionDAO.getActiveSessions();
        for(Session session : sessions){
            UserOnline  userOnline = new UserOnline();
            Object userInfo = new UserInfo();
            SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
            if(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)==null){
                continue;
            }else {
                System.out.println(session.getAttribute("userInfo"));
                //UserInfo user = (UserInfo) session.getAttribute("userInfo");
                principalCollection = (SimplePrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                userInfo = principalCollection.getPrimaryPrincipal();
                userOnline.setId((String) session.getId());
                userOnline.setHost(session.getHost());
                //userOnline.setUsername(user.getUsername());
                userOnline.setStartTimestamp(session.getStartTimestamp());
                userOnline.setLastAccessTime(session.getLastAccessTime());
                userOnline.setUserInfo(userInfo);
                Long timeout = session.getTimeout();
                if(timeout==0L){
                    userOnline.setStatus("离线");
                }else{
                    userOnline.setStatus("在线");
                }
                userOnline.setTimeout(timeout);
                userList.add(userOnline);
            }
        }
        return userList;
    }

    @Override
    public boolean forceLogout(String sessionId) {
        Session session = sessionDAO.readSession(sessionId);
        sessionDAO.delete(session);
        return true;
    }
}
